package cn.tedu.coolshark.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadController {
    //从application.properties配置文件中获取配置信息
    @Value("${dirPath}")
    private String dirPath;

    @RequestMapping("/upload")
    public String upload(MultipartFile pic) throws IOException {
        System.out.println("pic = " + pic);
        String fileName = pic.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;
        System.out.println(fileName);
        String dirPath = "C:/files";
        File dirFile = new File(dirPath);
        //文件夹如果不存在则创建
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //得到文件的完整路径
        String filePath = dirPath+"/"+fileName;
        //保存文件到上面路径  异常抛出
        pic.transferTo(new File(filePath));
        return "/"+fileName;
    }
    @RequestMapping("/remove")
    public void remove(String url){
        //得到文件的完整路径
        String filePath = dirPath+url;
        new File(filePath).delete();
    }
}
